package main

import (
	"ScadaDaemon/common"
	"ScadaDaemon/logging"
	"ScadaDaemon/script"
	"ScadaDaemon/service"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"
)

type program struct {
}

func (p *program) Start(s service.Service) error {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Printf("E! %s", err)
		return err
	}
	if dir == "" {
		dir, _ = os.Getwd()
		if err != nil {
			log.Printf("E! %s", err)
			return err
		}
	}

	fmt.Printf("当前路径%s\n", dir)
	// 初始化配置
	common.InitConfig(dir)
	// 初始化日誌
	logging.InitLogging(dir)
	log.Printf("ScadaDaemon開始運行...\n")
	if err != nil {
		log.Printf("%v,Application exit\n", err)
		os.Exit(0)
	}
	go p.run()
	log.Printf("ScadaDaemon成功運行...\n")
	return nil
}

//程序入口
func (p *program) run() {

	for {
		script.ExeCommand(common.Conf.AppInfos)
		time.Sleep(time.Duration(common.Conf.MonitorCycle) * time.Second)
	}
}

func (p *program) Stop(s service.Service) error {
	log.Printf("ScadaDaemon停止運行...")
	return nil
}
func main() {
	//windows service
	svcConfig := &service.Config{
		Name:        "ScadaDaemon",
		DisplayName: "ScadaDaemon",
		Description: "scada daemon process",
	}
	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal("E! " + err.Error())
	}
	if len(os.Args) > 1 {
		if os.Args[1] == "install" {
			s.Install()
			log.Println("安装服务成功\n")
		}
		if os.Args[1] == "uninstall" {
			s.Uninstall()
			log.Println("卸载服务成功\n")
		}
		if os.Args[1] == "restart" {
			s.Restart()
			log.Println("重启服务成功\n")
		}
		if os.Args[1] == "start" {
			s.Start()
			log.Println("启动服务成功\n")
		}
		if os.Args[1] == "stop" {
			s.Stop()
			log.Println("停止服务成功\n")
			return
		}
	}
	err = s.Run()
	if err != nil {
		log.Println("E! " + err.Error())
	}
}
